<template>
  <view class="head"
  style="background-color: #ffcc00;
  height: 180rpx;
  display: flex;">
    <img
    style="height: 50rpx;
    width: 50rpx;
    padding: 10rpx;
    margin-top: 15%;"  
    src="../../../static/tabbar/返回.png" alt="" @click="handleReturn"></img>
    <view style="
    height: fit-content;
     margin-top: 15%;
     margin-left: 30%;
     font-size: 32rpx;"
     >客户端-首页</view>
  </view>
  
  <view v-if="loading" class="loading-overlay">
    <view class="loading-content">
      <image src="../../../static/icons/loading.gif" class="loading-icon"></image>
      <text>加载中...</text>
    </view>
  </view>

  <view v-else class="page">
    
    <wd-search v-model="value" placeholder-left hide-cancel maxlength="10" class="search-wrapper" @search="search" />
    <!-- 公司福利发放模块 -->
    <view class="swiper-container">
      <wd-swiper
        :list="swiperList"
        autoplay
        v-model:current="current"
        :indicator="{ type: 'fraction' }"
        indicatorPosition="bottom-right"
      >
        <template #item="{ item }">
          <image 
            :src="item" 
            mode="aspectFill" 
            style="width: 100%; height: 100%;"
            @error="() => handleImageError(item)"
          />
        </template>
      </wd-swiper>
      <wd-button custom-class="custom-shadow" @click="handleBannerDetail(current)">立即了解</wd-button>
    </view>
    <view class="notice" @click="handleNoticeClick">
      <image src="../../../static/icons/notice.svg" alt="" />
      <text class="label">通知</text>
      <view class="split"></view>
      <text class="value">{{ noticeContent }}</text>
      <wd-icon name="arrow-right" size="22rpx" style="margin-left: 32rpx; color: #c7c7cc"></wd-icon>
    </view>

    <view class="nav" style="display: grid; grid-template-columns: repeat(5, 1fr); gap: 16rpx;">
    <view 
      v-for="(item, i) in navItems" 
      :key="i" 
      class="nav-item"
      :class="activeNav === i ? 'active' : ''"
      @click="handleNavItemClick(item.id, item.serviceType, item.title)"
    >
    
      <view class="icon-container">
        <image :src="item.url" style="width: 43rpx; height: 43rpx;" />
      </view>
      <text class="nav-item-title">{{ item.title }}</text>
    </view>
  </view>

    <view class="content">
      <text class="title">活动专区</text>
      <view class="list">
        <view 
          v-for="(item, index) in messageList" 
          :key="index" 
          class="list-item"
          @click="handleArticleClick(item.articleId, item.richText)"
        >
          <image :src="item.cover" />
          <text>{{ item.title }}</text>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
import usePage from "@/hooks/usePage.js"
import useLoading from "@/hooks/useLoading.js"
import { ref, onMounted, computed } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import { getBannerList, getNoticeList } from '@/api/content/banner'
import { getArticleContent, getActivityArticle } from '@/api/content/article'
import { getButtons } from '@/api/services/buttons'
import { getServices } from '@/api/services/services'
import { getWxUserInfo } from '@/api/wxlogin/wxlogin'
const handleReturn = () => {
  uni.navigateTo({url:'/pages/entrance/index'})
}
const { loading, setLoading } = useLoading()

const { systemBarHeight, menuBotton } = usePage()

// 修改 swiperList 为从接口获取
const richText = ref([])
const swiperList = ref([])
const buttons = ref([])
const services = ref([])

const fetchBannerData = async () => {
  try {
    const res = await getBannerList()
    console.log('原始banner数据:', res.data)
    if (res.data && Array.isArray(res.data)) {
      swiperList.value = res.data.map(item => item.url)
      richText.value = res.data.map(item => item.richText) // 存储富文本内容
      console.log('富文本数据:', richText.value)
    } else {
      throw new Error('返回的 banner 数据格式不正确')
    }
  } catch (err) {
    console.error('获取 banner 数据出错:', err)
    swiperList.value = [{
      url: '/static/images/default-banner.jpg', // 出错时使用默认图片
      richText: ''
    }]
    uni.showToast({
      title: '获取 banner 数据失败，请稍后重试',
      icon: 'none'
    })
  }
}

// 获取按钮数据
const fetchButtons = async () => {
  try {
    const res = await getButtons()
    console.log('接口返回数据:', res)
    console.log('接口返回的 data:', res.data)
    // 增加数据检测机制
    if (!res || !res.data || !Array.isArray(res.data)) {
      throw new Error('返回的按钮数据格式不正确')
    }
    // 直接使用返回的数据，不需要过滤 buttonId 为 0 的情况
    buttons.value = res.data.map(item => ({
      id: item.id || 0, // 默认值为 0
      buttonName: item.buttonName || '未知按钮', // 默认值为 '未知按钮'
      buttonImage: item.buttonImage || '/static/images/default-button.png' // 默认图片路径
    }))
    console.log('获取按钮数据成功', buttons.value)
  } catch (err) {
    console.error('请求按钮数据出错:', err)
    uni.showToast({
      // title: '按钮数据失败，请稍后重试获取',
      title: err.message,
      icon: 'none'
    })
  }
}

// 获取服务数据
const fetchServices = async () => {
  try {
    const res = await getServices()
    services.value = res.data
    console.log('获取服务数据成功', services.value)
  } catch (err) {
    console.error('请求服务数据出错:', err)
  }
}

// 获取用户信息
if(uni.getStorageSync('isLoggedIn')){
  const fetchUserInfo = async () => {
    const userId = uni.getStorageSync('userId')
    const res = await getWxUserInfo(userId)
    console.log('获取用户信息成功', res)
  }
}

// 获取活动专区文章数据
const fetchActivityArticles = async () => {
  try {
    const res = await getActivityArticle()
   
    if (res.code === 200 && Array.isArray(res.data)) {
      // 过滤 type 为 article1 的数据
      const filteredData = res.data.filter(item => item.type === 'article1')
      // 转换为 messageList 需要的格式
      messageList.value = filteredData.map(item => ({
        title: item.name,
        cover: item.image,
        articleId: item.id, // 添加文章ID
        richText: item.content // 添加富文本内容
      }))
      console.log('活动专区文章数据:', messageList.value)
    } else {
      throw new Error('获取活动专区文章数据失败')
    }
  } catch (err) {
    console.error('获取活动专区文章数据出错:', err)
    uni.showToast({
      title: '获取活动专区文章数据失败，请稍后重试',
      icon: 'none'
    })
  }
}

// 添加获取通知内容的函数
const fetchNotice = async () => {
  try {
    console.log('开始获取通知内容');
    const res = await getNoticeList();
    console.log('通知接口返回:', res);
    if (res.code === 200 && Array.isArray(res.data)) {
      const type1Notice = res.data.find(item => item.noticeType === 'type1');
      console.log('找到type1通知:', type1Notice);
      if (type1Notice) {
        noticeContent.value = type1Notice.notice;
        console.log('通知内容已更新:', noticeContent.value);
      } else {
        console.log('未找到type1通知');
      }
    } else {
      console.log('返回数据格式不正确');
    }
  } catch (err) {
    console.error('获取通知失败:', err);
    noticeContent.value = "客户端小程序上线啦！";
    console.log('使用默认通知内容');
  }
};

// 在页面加载时获取数据
onMounted(async () => {
  try {
    // 设置加载状态为 true
    setLoading(true)
    await Promise.all([
      fetchActivityArticles(),
      fetchNotice(),
      fetchBannerData(),
      fetchButtons(),
      fetchServices(),
      fetchUserInfo()
    ])
  } catch (err) {
    console.error('页面加载时出错:', err)
    // uni.showToast({
    //   title: '加载数据失败，请重试',
    //   icon: 'none'
    // })
  } finally {
    // 完成后设置加载状态为 false
    setLoading(false)
  }
})

const navItems = computed(() => {
  // 先获取前9个按钮
  const firstNineButtons = buttons.value.slice(0, 9).map(button => ({
    id: button.id,
    title: button.buttonName,
    url: button.buttonImage,
    serviceType: 'all'
  }))

  // 添加第10个固定按钮
  const allServicesButton = {
    id: buttons.value[0]?.id || 0, // 使用第一个按钮的ID
    title: '全部需求',
    url: 'https://cloud-minapp-47994.cloud.ifanrusercontent.com/1uKYGcEZ50DK2tm6.png',
    serviceType: 'all'
  }

  return [...firstNineButtons, allServicesButton]
})

const messageList = ref([
  // {
  //   title: "医疗护理员",
  //   cover: "https://cloud-minapp-47896.cloud.ifanrusercontent.com/1tNXnvS1F5bP4DBo.jpg",
  //   articleId: 1
  // },
  // {
  //   title: "巾帼风采，芳华绽放",
  //   cover: "https://cloud-minapp-47896.cloud.ifanrusercontent.com/1tNXnvwwo9rnyPpn.jpg",
  //   articleId: 2
  // },
])

const noticeContent = ref("")

const handleNavItemClick = (buttonId, serviceType, buttonName) => {
  uni.navigateTo({
    url: `/pages/customer-platform/index/menu/homeClean/homeClean?buttonId=${Number(buttonId)}&buttonName=${encodeURIComponent(buttonName)}`,
    success: () => {
      uni.$emit('updateServices', services.value);
    }
  });
};

const handleClick = () => {
  uni.navigateTo({ url: "/pages/login/index" })
}

const handleArticleClick = async (id, richText) => {
  try {
    if (richText) {
      uni.navigateTo({
        url: `/pages/customer-platform/index/content-detail?content=${encodeURIComponent(richText)}`
      });
    } else {
      const res = await getArticleContent(id);
      uni.navigateTo({
        url: `/pages/customer-platform/index/content-detail?content=${encodeURIComponent(res.data)}`
      });
    }
  } catch (err) {
    console.error('获取文章内容失败:', err);
    uni.showToast({
      title: '获取文章内容失败',
      icon: 'none'
    });
  }
};

const handleNoticeClick = () => {
  uni.navigateTo({
    url: `/pages/notice/detail?content=${encodeURIComponent(noticeContent.value)}`
  });
};

const handleBannerDetail = (index) => {
  if (richText.value[index]) {
    uni.navigateTo({
      url: `/pages/banner/detail?content=${encodeURIComponent(richText.value[index])}`
    })
  } else {
    uni.showToast({
      title: '该图片暂无详细内容',
      icon: 'none',
      duration: 2000
    })
  }
}

const handleImageError = (item) => {
  console.error('图片加载失败:', item)
  item = '/static/images/default-banner.jpg' // 替换为默认图片
  uni.showToast({
    title: '图片加载失败',
    icon: 'none',
    duration: 1500
  })
}

</script>

<style scoped lang="scss">
.nav {
  display: grid;
  grid-template-columns: repeat(5, 1fr); // 创建五列等宽的网格
  gap: 16rpx; // 设置网格项之间的间距
  padding: 0 16rpx;
  background-color: #fff;
}

.nav-item {
  text-align: center;
  background-color: #fff;
  border-radius: 8rpx;
  transition: all 0.2s ease-in-out;
  border: none;

  &:active {
    transform: scale(0.98);
  }

  &.active {
    background-color: #12b858;
    color: #fff;

    .nav-item-title,
    .wd-icon {
      color: #fff !important;
    }
  }
}

.icon-container {
  padding: 16rpx 0;
  display: flex;
  justify-content: center;
  align-items: center;

  image {
    width: 43rpx;
    height: 43rpx;
  }
}

.nav-item-title {
  font-size: 24rpx;
  color: #1a1a1a;
}
.page {
  padding: 0 24rpx;
  background-color: #f5f6fa;

  &-hd {
    // padding: 19rpx 0;
    font-family: PingFang SC;
    font-size: 36rpx;
    font-variation-settings: "opsz" auto;
    font-weight: 500;
    line-height: normal;
    color: #1a1a1a;
  }

  :deep(.wd-search) {
    padding: 16rpx 0px !important;
    background-color: transparent !important;
  }

  .swipper {
    height: 324rpx;
    margin: 0 auto;
    margin-top: 16rpx;
    border-radius: 24rpx;
    overflow: hidden;

    image {
      width: 100%;
      height: 100%;
    }
  }

  .nav {
    margin-bottom: 24rpx;

    :deep(.wd-grid) {
      .wd-grid-item {
        width: calc(20% - 16rpx) !important;
        /* width: 164rpx !important; */
        height: 138rpx;
        border-radius: 16rpx;
        margin: 0 8rpx 8px;

        &__text {
          margin-top: 10.5rpx;
          font-family: PingFang SC;
          font-size: 24rpx;
          font-weight: normal;
          line-height: normal;
          color: #1a1a1a;
        }
      }

      .active {
        .wd-grid-item__content {
          background: #12b858 !important;
        }

        .wd-grid-item__text {
          color: #fff !important;
        }

        .wd-icon {
          color: #fff !important;
        }
      }
    }
  }

  .swiper-container {
    margin-bottom: 24rpx;
    position: relative;
    border-radius: 24rpx;
    overflow: hidden;

    .title {
      position: absolute;
      top: 0rpx;
      left: 0rpx;
      color: #fff;
      padding: 6rpx 16rpx;
      border-radius: 24rpx;
      background: rgba(#000, 0.6);
    }
    :deep() {
      .custom-shadow {
        position: absolute;
        bottom: 46rpx;
        left: 46rpx;
        color: #89281f;
        background-color: #f2d39c;
        box-shadow:
          0 3px 1px -2px rgb(0 0 0 / 20%),
          0 2px 2px 0 rgb(0 0 0 / 14%),
          0 1px 5px 0 rgb(0 0 0 / 12%);
      }
    }
  }

  .notice {
    display: flex;
    align-items: center;
    height: 80rpx;
    padding: 0 33.67rpx;
    margin: 24rpx 0 32rpx;
    background-color: #fff;
    border-radius: 16rpx;

    img,
    image {
      width: 26rpx;
      height: 26rpx;
    }

    .label {
      margin-left: 16rpx;
      font-family: PingFang SC;
      font-size: 26rpx;
      /* 文本/正文 */
      color: #1a1a1a;
    }

    .split {
      width: 2rpx;
      height: 24rpx;
      margin: 0 24rpx;
      background-color: #ececec;
    }

    .value {
      flex: 1;
      overflow: hidden;
      font-family: PingFang SC;
      font-size: 26rpx;
      color: #8c8c8c;
      text-overflow: ellipsis;
      letter-spacing: 0em;
      white-space: nowrap;
    }
  }

  :deep(.search-wrapper) {
    // height: 72rpx;
    // padding: 0;
    // margin-bottom: 24rpx;
    // border-radius: 16rpx;

    .wd-search__input {
      background-color: #fff;

      input::placeholder {
        font-size: 28rpx;
      }
    }

    .wd-icon {
      z-index: 999;
      width: 28rpx;
      height: 28rpx;
      color: #1a1a1a;
      transform: translateY(-20rpx);
    }
  }

  .content {
    padding: 16rpx 32rpx;
    background-color: #fff;
    border-radius: 16rpx;

    .title {
      color: #ffc111;
    }
    .list {
      display: flex;
      flex-wrap: wrap;
      gap: 16rpx
    }

    .list-item {
      width: calc(50% - 10rpx);
      display: flex;
      flex-direction: column;
      gap: 16rpx;
      align-items: center;
      justify-content: space-between;
      padding: 16rpx 0;
      border-color: #f2f2f7;
      border-style: solid;
      border-width: 0px 0px 1rpx 0px;

      text {
          /* 设置为WebKit内核的弹性盒子模型 */
          overflow: hidden;
          /* 隐藏超出范围的内容 */
          font-size: 27rpx;
          font-weight: normal;
          line-height: normal;
          color: #1a1a1a;
          text-overflow: ellipsis;
          white-space: nowrap;
        }


      image {
        width: 94%;
        min-width: 182rpx;
        height: 168rpx;
        border-radius: 8rpx;
      }
    }
  }

  .loading-overlay {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background-color: rgba(255, 255, 255, 0.9);
    display: flex;
    justify-content: center;
    align-items: center;
    z-index: 999;

    .loading-content {
      display: flex;
      flex-direction: column;
      align-items: center;
      
      .loading-icon {
        width: 100rpx;
        height: 100rpx;
        margin-bottom: 20rpx;
      }
      
      text {
        font-size: 28rpx;
        color: #666;
      }
    }
  }
}
</style>
